using System;
using OpenRay;
using System.Collections.Generic;

using System.Drawing;
using System.Drawing.Imaging;
using System.Diagnostics;

namespace SideBySide
{
	class MainClass
	{
		private static void SavePNG( FrameBuffer fb, string s ) {
			Bitmap bmp = new Bitmap(fb.Width, fb.Height );
			
			for ( int y = 0; y < fb.Height; y++ )
			{
				for ( int x = 0; x < fb.Width; x++ )
				{
					float[] color = fb.GetArgb(x,y);
					
					for( int i = 0; i < 4; i++ )
					{
						color[i] = (float)Math.Max( 0, Math.Min( 1f, color[i] )  );	
					}
					
					bmp.SetPixel(x, y, System.Drawing.Color.FromArgb( 255, (int)(color[1] * 255f), (int)(color[2] * 255f), (int)(color[3] * 255f) ) );
				}
			}
			
			bmp.Save(s, ImageFormat.Png );
			bmp.Dispose();
		}
		
		private static OpenRay.PhongMaterial CreateMaterial( OpenRay.Color d )
		{
			OpenRay.Color[] ambient = new OpenRay.Color[2];
			OpenRay.Color[] diffuse = new OpenRay.Color[2];
			OpenRay.Color[] specular = new OpenRay.Color[2];
			OpenRay.Color[] emissive = new OpenRay.Color[2];
			float[] shininess = new float[2];
			
			ambient[0] = new OpenRay.Color( 0.2f, 0.2f, 0.2f, 1f );
			ambient[1] = ambient[0];
			
			diffuse[0] = d;
			diffuse[1] = d;
			
			specular[0] = new OpenRay.Color( 0.5f, 0.5f, 0.5f, 1f );
			specular[1] = specular[0];
			
			emissive[0] = new OpenRay.Color( 0f, 0f, 0f, 1f );
			emissive[1] = emissive[0];
			
			shininess[0] = 10f;
			shininess[1] = shininess[0];
			
			return new OpenRay.PhongMaterial(ambient, diffuse, specular, emissive, shininess );
		}
		
		private static List<OpenRay.Light> CreateLighting()
		{
			List<OpenRay.Light> ret = new List<OpenRay.Light>();
			
			OpenRay.Color dim = new OpenRay.Color(0.2f, 0.2f, 0.2f, 1f );
			OpenRay.Color white = new OpenRay.Color(1f, 1f, 1f, 1f);
			OpenRay.Color black = new OpenRay.Color(0f, 0f, 0f, 1f);
			
			ret.Add( new OpenRay.DirectionalPhongLight( dim, black, black, new Vector( 1f, 0f, 0f ), null ) );
			ret.Add( new OpenRay.DirectionalPhongLight( black, white, white, new Vector( -1f, 1f, 1f ), null ) );
			
			return ret;
		}
		
		public static void Main (string[] args)
		{			
			Stopwatch watch = new Stopwatch();
			
			ObjReader o = new ObjReader("../../../teapot.obj");
			
			OpenRay.Material[] m = new OpenRay.Material[1];
			m[0] = CreateMaterial( new OpenRay.Color( 1f, 0f, 0f, 1f ) );
			
			watch.Start();
			SavePNG( o.Draw( m, CreateLighting() ), "TestTeapot.png" );
			watch.Stop();
			
			Console.WriteLine("Elapsed: {0}",watch.Elapsed);
			Console.WriteLine("In milliseconds: {0}",watch.ElapsedMilliseconds);
			Console.WriteLine("In timer ticks: {0}",watch.ElapsedTicks);
		}
	}
}

